import React, { useState } from "react";
import { 
  Avatar, Card, Badge, Button, Row, Col, Divider, 
  Modal, Form, Input, Checkbox, message,Typography, 
  Tag
} from "antd";
import { 
  UserOutlined, 
  CarOutlined, 
  EnvironmentOutlined, 
  StarOutlined, 
  GiftOutlined,
  ProfileOutlined,
  HeartOutlined,
  SettingOutlined,
  LeftOutlined,
  LockOutlined,
  PhoneOutlined,
  MailOutlined
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { OrderStatus, OrderStatusText } from '../types/order';
const { Text } = Typography;

interface UserInfo {
  name: string;
  phone: string;
  email: string;
  points: number;
  level: string;
  orders: Order[];
}

interface Order {
  id: string;
  date: string;
  total: number;
  status: OrderStatus;
  userId: string;
  items: {
    name: string;
    price: number;
    quantity: number;
    image: string;
  }[];
}

export default function ProfilePage({
  isMobile,
  orders, 
  setActiveTab, 
  userInfo,
  onLogout,
  isLoggedIn,
  onLogin,
  onViewOrderDetail
}: { 
  isMobile: boolean;
  orders: Order[]; 
  setActiveTab: (tab: string) => void;
  userInfo: any;  
  onLogout: () => void;  
  isLoggedIn: boolean;
  onLogin: (userData: any) => void;
  onViewOrderDetail: (orderId: string) => void;
}) {
  const [form] = Form.useForm();
  const [loginVisible, setLoginVisible] = useState(false);
  const [isLoggingIn, setIsLoggingIn] = useState(false);
  const avatarSize = isMobile ? 48 : 64;
  const navigate = useNavigate();
  
  const userMenuItems = [
    { icon: <CarOutlined />, title: "待发货", count: 2 },
    { icon: <EnvironmentOutlined />, title: "待收货", count: 0 },
    { icon: <StarOutlined />, title: "待评价", count: 3 },
    { icon: <GiftOutlined />, title: "退换货", count: 1 }
  ];

  const profileMenuItems = [
    { icon: <ProfileOutlined />, title: "我的订单", desc: "查看全部订单" },
    { icon: <HeartOutlined />, title: "我的收藏", desc: "收藏的商品" },
    { icon: <EnvironmentOutlined />, title: "收货地址", desc: "管理收货地址" },
    { icon: <GiftOutlined />, title: "优惠券", desc: "查看可用优惠券" },
    { icon: <SettingOutlined />, title: "设置", desc: "账户设置" }
  ];

  const handleLogin = async (values: any) => {
    setIsLoggingIn(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      if (values.username === "张三" && values.password === "123456") {
        const userData = {
          name: "张三",
          phone: "138****1234",
          email: "zhangsan@bjtu.edu.cn",
          points: 1280,
          level: "黄金会员",
          orders: orders
        };
        
        if (values.remember) {
          localStorage.setItem('userInfo', JSON.stringify(userData));
        } else {
          localStorage.removeItem('userInfo');
        }

        onLogin(userData);
        message.success("登录成功！");
        setLoginVisible(false);
        form.resetFields();
      } else {
        message.error("用户名或密码错误");
      }
    } finally {
      setIsLoggingIn(false);
    }
  };

  // 过滤出当前用户的订单
  const userOrders = orders.filter(order => order.userId === userInfo?.id);

  return (
    <div style={{ padding: "12px 0" }}>
      <Card style={{ marginBottom: 12 }} bodyStyle={{ padding: isMobile ? 10 : 12 }}>
        <div style={{ display: "flex", alignItems: "center" }}>
          <Avatar 
            size={avatarSize} 
            icon={<UserOutlined />} 
            style={{ backgroundColor: isLoggedIn ? "#1890ff" : "#bfbfbf" }} 
          />
          {isLoggedIn && userInfo ? (
            <div style={{ marginLeft: 14, flex: 1 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <h3 style={{ margin: 0, fontSize: isMobile ? 16 : 18 }}>{userInfo.name}</h3>
                <Button 
                  type="primary" 
                  size={isMobile ? "small" : "middle"}
                  onClick={onLogout}
                >
                  退出
                </Button>
              </div>
              <div style={{ marginTop: 8, display: "flex", flexWrap: "wrap" }}>
                <div style={{ 
                  background: "#e6f7ff", 
                  padding: "2px 8px", 
                  borderRadius: 4, 
                  marginRight: 8,
                  marginBottom: 8,
                  fontSize: isMobile ? 11 : 12
                }}>
                  <PhoneOutlined style={{ marginRight: 4 }} />
                  {userInfo.phone}
                </div>
                <div style={{ 
                  background: "#e6f7ff", 
                  padding: "2px 8px", 
                  borderRadius: 4,
                  marginBottom: 8,
                  fontSize: isMobile ? 11 : 12
                }}>
                  <MailOutlined style={{ marginRight: 4 }} />
                  {userInfo.email}
                </div>
              </div>
              <div style={{ marginTop: 8, display: "flex", fontSize: isMobile ? 12 : 13 }}>
                <div style={{ color: "#666", marginRight: 16 }}>
                  <span style={{ color: "#ffc53d", marginRight: 4 }}>{userInfo.points}</span>积分
                </div>
                <div style={{ color: "#666" }}>
                  <span style={{ color: "#faad14", marginRight: 4 }}>{userInfo.level}</span>
                </div>
              </div>
            </div>
          ) : (
            <div style={{ marginLeft: 14, flex: 1 }}>
              <h3 
                style={{ 
                  margin: 0, 
                  fontSize: isMobile ? 16 : 18, 
                  cursor: 'pointer',
                  color: '#1890ff'
                }}
                onClick={() => setLoginVisible(true)}
              >
                点击登录
              </h3>
              <p style={{ margin: "5px 0 0", fontSize: isMobile ? 12 : 13, color: "#666" }}>
                登录后享受更多权益
              </p>
            </div>
          )}
        </div>
      </Card>
      
      {/* {isLoggedIn && userInfo && userOrders.length > 0 && (
        <Card 
          title="我的订单" 
          style={{ marginBottom: 12 }}
          headStyle={{ padding: isMobile ? "10px 12px" : "12px 16px" }}
          bodyStyle={{ padding: 0 }}
        >
          {userOrders.slice(0, 3).map((order) => (
            <div 
              key={order.id}
              style={{ 
                padding: isMobile ? "12px 14px" : "12px 16px", 
                display: "flex", 
                alignItems: "center", 
                borderBottom: "1px solid #f0f0f0",
                cursor: "pointer"
              }}
              onClick={() => onViewOrderDetail(order.id)}
            >
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", justifyContent: "space-between" }}>
                  <Text strong>订单号: {order.id}</Text>
                  <Tag color={order.status === OrderStatus.PAID ? "green" : "blue"}>
                    {OrderStatusText[order.status]}
                  </Tag>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8 }}>
                  <Text type="secondary">{order.date}</Text>
                  <Text strong>¥{(order.total || 0).toFixed(2)}</Text>
                </div>
              </div>
              <div style={{ color: "#bfbfbf", marginLeft: 12 }}>
                <LeftOutlined rotate={180} />
              </div>
            </div>
          ))}
          <div 
            style={{ 
              padding: isMobile ? "12px 14px" : "12px 16px", 
              textAlign: "center",
              color: "#1890ff",
              cursor: "pointer"
            }}
            onClick={() => setActiveTab('orderList')}
          >
            查看全部订单
          </div>
        </Card>
      )} */}
      <Card style={{ marginBottom: 12 }} bodyStyle={{ padding: isMobile ? 10 : 12 }}>
        <Row gutter={[8, 12]}>
          {userMenuItems.map((item, index) => (
            <Col span={6} key={index}>
              <div style={{ textAlign: "center" }}>
                <Badge count={item.count > 0 ? item.count : null} style={{ backgroundColor: "#52c41a" }}>
                  <Button
                    shape="circle"
                    icon={item.icon}
                    style={{ 
                      fontSize: isMobile ? 18 : 20, 
                      width: isMobile ? 36 : 40, 
                      height: isMobile ? 36 : 40, 
                      display: "flex", 
                      alignItems: "center", 
                      justifyContent: "center" 
                    }}
                  />
                </Badge>
                <div style={{ fontSize: isMobile ? 12 : 13, marginTop: 6 }}>{item.title}</div>
              </div>
            </Col>
          ))}
        </Row>
      </Card>

      <Card bodyStyle={{ padding: 0 }}>
        {profileMenuItems.map((item, index) => (
          <React.Fragment key={index}>
            <div
              style={{ 
                padding: isMobile ? "12px 14px" : "12px 16px", 
                display: "flex", 
                alignItems: "center", 
                cursor: "pointer" 
              }}
              onClick={() => {
                if (item.title === "我的订单") {
                  setActiveTab('orderList');
                }
              }}
            >
              <div style={{ fontSize: isMobile ? 18 : 20, width: 24, display: "flex", alignItems: "center" }}>
                {item.icon}
              </div>
              <div style={{ marginLeft: 12, flex: 1 }}>
                <div style={{ fontSize: isMobile ? 14 : 16 }}>{item.title}</div>
                <div style={{ fontSize: isMobile ? 11 : 13, color: "#999" }}>{item.desc}</div>
              </div>
              <div style={{ color: "#bfbfbf" }}>
                <LeftOutlined rotate={180} />
              </div>
            </div>
            {index < profileMenuItems.length - 1 && <Divider style={{ margin: 0 }} />}
          </React.Fragment>
        ))}
      </Card>

      <Modal
        title="登录账号"
        open={loginVisible}
        onCancel={() => setLoginVisible(false)}
        footer={null}
        width={isMobile ? "85%" : 400}
        destroyOnClose
        maskClosable={false}
      >
        <Form
          form={form}
          name="login_form"
          initialValues={{ remember: true }}
          onFinish={handleLogin}
          autoComplete="off"
          layout="vertical"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: '请输入用户名!' },
              { pattern: /^[\u4e00-\u9fa5]{2,6}$/, message: '请输入2-6位中文姓名' }
            ]}
          >
            <Input 
              prefix={<UserOutlined />} 
              placeholder="请输入用户名" 
              size="large"
              allowClear
            />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码!' },
              { min: 6, message: '密码长度至少6位' },
              { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/, message: '密码需包含字母和数字' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码"
              size="large"
              allowClear
              disabled={isLoggingIn}
            />
          </Form.Item>

          <Form.Item name="remember" valuePropName="checked">
            <Checkbox disabled={isLoggingIn}>记住我</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              block
              size="large"
              style={{ marginBottom: 12 }}
              loading={isLoggingIn}
              disabled={isLoggingIn}
            >
              登录
            </Button>
            <div style={{ textAlign: "center", color: "#999", fontSize: 13 }}>
              提示：使用用户名 "张三"，密码 "123456" 登录
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}